import { Component, OnInit, InjectionToken } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { RouterModule, Routes, Router, ActivatedRoute, ParamMap } from '@angular/router';
import { MdlSnackbarService } from '@angular-mdl/core';
import { SelectItem, ConfirmationService } from 'primeng/primeng';
import { Location } from '@angular/common';
import { Schedule } from './schedule.model';
import { ScheduleService } from './schedule.service';
import { switchMap } from 'rxjs/operators';
@Component({
  templateUrl: './schedule-detail.component.html',
  styleUrls: ['./schedule-detail.component.scss'],
  providers: [ ScheduleService ]
})
export class ScheduleDetailComponent implements OnInit {

  groupName: string;
  jobName: string;
  scheduleForm: FormGroup;
  groups: SelectItem[] = [];
  selectedGroup: SelectItem = {'value':''};
  schedule: Schedule = new Schedule({});

  constructor(
      private fb: FormBuilder,
      private router: Router,
      private location: Location,
      private route: ActivatedRoute,
      private scheduleService: ScheduleService,
      private mdlSnackbarService: MdlSnackbarService,
      private confirmationService: ConfirmationService) {
  }

  ngOnInit() {
      this.route.paramMap.pipe(
        switchMap((params: ParamMap) => {
            this.groupName = params.get('groupName');
            this.jobName = params.get('jobName');
            return this.scheduleService.showJobDetail(this.groupName, this.jobName);
          })
      ).subscribe(data => {
          this.schedule = new Schedule(data);
          this.scheduleService.listGroups().subscribe(data => {
              data.forEach(element => {
                  let grp = {'label': element['systemName'],'value': element['systemUrl']};
                  this.groups.push(grp);
                  if(this.groupName == element['systemUrl']){
                      this.selectedGroup = grp;
                  }
              });
              this.buildForm();
          })
      }, error => console.error(error));
      
      this.buildForm();
  }
  /**新增表单 */
  saveUpdate() {
    this.scheduleService.saveUpdateSchedule(this.scheduleForm.value)
      .subscribe(data => {
        this.mdlSnackbarService.showToast('数据保存成功！');
      });
  }

  groupChange($event : any){
    this.groups.forEach(data =>{
      if(data.value == $event.value){
        this.selectedGroup = data;
      }
    })
  }

  goBack(){
    if (this.scheduleForm.dirty) {
        this.confirmationService.confirm({
          header: '确认',
          message: '您确定要放弃保存修改的记录吗？',
          accept: () => {
            this.location.back();
          }
        });
      } else {
        this.location.back();
      }
  }
  buildForm(): void {
      this.scheduleForm = this.fb.group({
          'jobId': [this.schedule.jobId],
          'jobGroup': [this.selectedGroup.value],
          'jobName': [this.schedule.jobName],
          'cronExpression': [this.schedule.cronExpression],
          'interfaceName': [this.schedule.interfaceName],
          'desc': [this.schedule.desc]
      });
      this.scheduleForm.valueChanges
          .subscribe(data => this.onValueChanged(data));
      this.onValueChanged();
  }

  onValueChanged(data?: any) {
      if (!this.scheduleForm) { return; }
      const form = this.scheduleForm;
      for (const field in this.formErrors) {
          this.formErrors[field] = '';
          const control = form.get(field);
          if (control && control.dirty && !control.valid) {
              const messages = this.validationMessages[field];
              for (const key in control.errors) {
                  this.formErrors[field] += messages[key] + ' ';
              }
          }
      }
  }

  formErrors = {
      'formName': ''
  };

  validationMessages = {
      'formName': {
          'required': '表单名称为必填项',
          'minlength': '数据源名称长度必须大于2',
          'maxlength': '数据源名称长度必须小于20'
      }
  };

}
